#include <Erc.h>
#include "erc_private.h"

static int _erc_init_count = 0;
int _erc_log_dom_global = -1;


Erc *
erc_new(const char *server,
        unsigned int port,
        const char *nickname)
{
   Erc *erc;

   EINA_SAFETY_ON_NULL_RETURN_VAL(server, NULL);
   EINA_SAFETY_ON_NULL_RETURN_VAL(nickname, NULL);

   erc = calloc(1, sizeof(Erc));
   if (!erc)
     {
        ERR("Failed to alloc");
        return NULL;
     }

   erc->con.nick = strdup(nickname);
   erc->con.server = strdup(server);

#define _EV(_a, _b, _c)                                                        \
   _a = ecore_event_handler_add(ECORE_CON_EVENT_SERVER#_b, _c, erc);

   _EV(erc->con.ev.add, ADD, _erc_event_connect);
   _EV(erc->con.ev.del, DEL, _erc_event_disconnect);
   _EV(erc->con.ev.data, DATA, _erc_event_data);
   _EV(erc->con.ev.error, ERROR, _erc_event_error);
   _EV(erc->con.ev.write, WRITE, _erc_event_write);
#undef _EV

   return NULL;
}

void
erc_free(Erc *erc)
{
   EINA_SAFETY_ON_NULL_RETURN(erc);

   free(erc->info.nick);
   free(erc->info.server);
}

int
erc_init(void)
{
   if (++_erc_init_count != 1)
     return _erc_init_count;

   if (!eina_init())
     {
        fprintf(stderr, "Erc can not initialize Eina\n");
        return --_erc_init_count;
     }

   _erc_log_dom_global = eina_log_domain_register("erc", EINA_COLOR_RED);
   if (_erc_log_dom_global < 0)
     {
        EINA_LOG_ERR("Erc can not create a general log domain");
        goto shutdown_eina;
     }

   if (!ecore_init())
     {
        ERR("Can not initialize Ecore");
        goto unregister_log_domain;
     }

   if (!ecore_con_init())
     {
        ERR("Can not initialize Ecore_Con");
        goto shutdown_ecore;
     }

shutdown_ecore:
   ecore_shutdown();
unregister_log_domain:
   eina_log_domain_unregister(_erc_log_dom_global);
   _erc_log_dom_global = -1;
shutdown_eina:
   eina_shutdown();
   return --_erc_init_count;
}

int
erc_shutdown(void)
{
   if (_erc_init_count <= 0)
     {
        ERR("Init count not greater than 0 in shutdown.");
        return 0;
     }
   if (--_erc_init_count) != 0)
     return _erc_init_count;

   ecore_con_shutdown();
   ecore_shutdown();
   eina_log_domain_unregister(_erc_log_dom_global);
   _erc_log_dom_global = -1;
   eina_shutdown();

   return _erc_init_count;
}
